
206 CHAPTER 4. RAILS-FLAVORED RUBY
the test is a block. The test method takes in a string argument (the description)
and a block, and then executes the body of the block as part of running the test
suite.
By the way, we’re now in a position to understand the line of Ruby I threw
into Section 1.4.2 to generate random subdomains:
13
('a'..'z').to_a.shuffle[0..7].join
Let’s build it up step-by-step:
>> ('a'..'z').to_a # An alphabet array
=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o",
"p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
>> ('a'..'z').to_a.shuffle # Shuffle it.
=> ["c", "g", "l", "k", "h", "z", "s", "i", "n", "d", "y", "u", "t", "j", "q",
"b", "r", "o", "f", "e", "w", "v", "m", "a", "x", "p"]
>> ('a'..'z').to_a.shuffle[0..7] # Pull out the first eight elements.
=> ["f", "w", "i", "a", "h", "p", "c", "x"]
>> ('a'..'z').to_a.shuffle[0..7].join # Join them together to make one string.
=> "mznpybuj"
Exercises
Solutions to the exercises are available to all Rails Tutorial purchasers here.
To see other people’s answers and to record your own, subscribe to the Rails
Tutorial course or to the Learn Enough All Access Bundle.
1. Using the range 0..16, print out the first 17 powers of 2.
2. Define a method called yeller that takes in an array of characters and
returns a string with an ALLCAPS version of the input. Verify that yel-
ler(['o', 'l', 'd']) returns "OLD". Hint: Combine map, up-
case, and join.
13
As noted in Chapter 1, in this case the code ('a'..'z').to_a.sample(8).join is an even more compact
way of getting the same result.